<template>
  <div class="v-mobile-wrapper">
    <van-cell-group inset style="margin: 0">
      <FormItem v-for="obj in forms" :key="obj.id" :tdId="obj.tdId" type="mobile" />
    </van-cell-group>
  </div>
</template>

<script setup lang="ts">
import * as toolUtils from './tools/utils'
import type { VTableForm } from '@/components/VTable/types'
import type { FormItem, FormValueItem } from './types'
import { ElMessage } from 'element-plus'
const tableForm = ref<VTableForm>({
  id: '',
  tables: [],
  forms: [],
  tableAttr: {
    title: '',
    bgColor: '',
    borderColor: ''
  }
})
// 表格单元格列表
const tables = computed(() => tableForm.value?.tables || [])
// 表格属性
const tableAttr = computed(() => tableForm.value?.tableAttr)
// 表单项列表
const forms = computed<FormItem[]>(() => tableForm.value?.forms || [])
// 输出表单数据
const formValueList = ref<FormValueItem[]>([])
provide('tables', {
  tables,
  tableAttr
})
// 表单数据及操作方法
provide('forms', {
  forms,
  getFormValueList: () => {
    return formValueList.value
  },
  getFormValue: (key: string) => {
    return formValueList.value.find((el) => el.form_input_id === key)?.form_input_value
  },
  // 更新表单列表
  updateFormValue: (key: string, value: string | number) => {
    formValueList.value = formValueList.value.map((el) => {
      if (el.form_input_id === key) {
        el.form_input_value = value
      }
      return el
    })
  }
})
defineExpose({
  // 新建
  init: (data: VTableForm, value: FormValueItem[]) => {
    if (data) {
      tableForm.value = JSON.parse(JSON.stringify(data))
      if (value.length) {
        formValueList.value = value
      } else {
        formValueList.value = tableForm.value.forms
          .map((obj) => {
            return toolUtils.initFormValue(obj)
          })
          .filter((el) => {
            return el.form_input_id
          })
      }
    }
  },
  setValue: (value: FormValueItem[]) => {
    if (value.length) {
      formValueList.value = value
    }
  },
  getValue: () => {
    const errorInfo = toolUtils.validateFormValue(formValueList.value, forms.value)
    // console.log(errorInfo, formValueList.value)
    if (errorInfo) return ElMessage.error(errorInfo)
    return formValueList.value
  }
})
</script>

<style lang="scss">
.v-mobile-wrapper {
  background-color: #ffffff;
}
</style>
